﻿function initialUserConfig(value) {
    if (value) {
    } else
        value = { user: window.userId, tabs: [] };
    window.Ext.util.Cookies.set('userConfig', window.Ext.encode(value));
}

function addTab(tabPanel, id, url, title) {
    var tab = tabPanel.getComponent(id);
    if (!tab)
        tab = tabPanel.add({
            id: id,
            title: title,
            closable: 'idTInfo' != id,
            loader: {
                url: url,
                renderer: "frame",
                loadMask: {
                    showMask: true,
                    msg: "Loading " + title + "..."
                }
            }
        });
    tabPanel.setActiveTab(tab);
}

function addTabAndSaveCookie(tabPanel, id, url, title, cookie, last) {
    if (cookie) {
    } else
        saveTabIntoCookie(id, url, title);

    var tab = tabPanel.getComponent(id);
    if (!tab)
        tab = tabPanel.add({
            id: id,
            title: title,
            closable: true,
            loader: {
                url: url,
                renderer: "frame",
                loadMask: {
                    showMask: false,
                    msg: "Loading " + title + "..."
                }
            },
            listeners: {
                close: removeTab
            }
        });
    if (cookie != true || last)
        tabPanel.setActiveTab(tab);
}

function removeTab(item) {
    var userConfig = window.Ext.util.Cookies.get('userConfig');
    if (userConfig || userConfig == null) {
    } else
        initialUserConfig();
    var config = window.Ext.decode(userConfig);
    if (config.user == window.userId) {
        for (var i = 0; i < config.tabs.length; i++)
            if (config.tabs[i].id == item.id)
                config.tabs.splice(i, 1);
        initialUserConfig(config);
    } else
        initialUserConfig();
}

function saveTabIntoCookie(id, url, title) {
    var userConfig = window.Ext.util.Cookies.get('userConfig');
    if (userConfig) {
    } else
        initialUserConfig();
    var config = window.Ext.decode(userConfig);
    if (config.user == window.userId) {
        config.tabs.push({ id: id, url: url, title: title });
        initialUserConfig(config);
    } else
        initialUserConfig();
}

function restorePreviousState() {
    var userConfig = window.Ext.util.Cookies.get('userConfig');
    if (userConfig) {
        var config = window.Ext.decode(userConfig);
        if (config.user == window.userId) {
            for (var i = 0; i < config.tabs.length; i++)
                addTabAndSaveCookie(window.App.TabPanel1, config.tabs[i].id, config.tabs[i].url, config.tabs[i].title, true, (i + 1) == config.tabs.length);
            return;
        }
    }
    initialUserConfig();
}